package com.example.aboutwork.phaser;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Phaser;

import static org.junit.Assert.assertEquals;

public class UseCase {


    public static void main(String[] args) {

        ExecutorService executorService = Executors.newCachedThreadPool();
        Phaser ph = new Phaser(1);

        assertEquals(0, ph.getPhase());

        executorService.execute(new LongRunningAction("thread-1", ph));
        executorService.execute(new LongRunningAction("thread-2", ph));
        executorService.execute(new LongRunningAction("thread-3", ph));

        ph.arriveAndAwaitAdvance();

        assertEquals(1, ph.getPhase());


        executorService.execute(new LongRunningAction("thread-4", ph));
        executorService.execute(new LongRunningAction("thread-5", ph));
        ph.arriveAndAwaitAdvance();

        assertEquals(2, ph.getPhase());

    }


}


class LongRunningAction implements Runnable {
    private final String threadName;
    private final Phaser ph;

    LongRunningAction(String threadName, Phaser ph) {
        this.threadName = threadName;
        this.ph = ph;
        ph.register();
    }

    @Override
    public void run() {
        ph.arriveAndAwaitAdvance();
        try {
            Thread.sleep(20);
            System.err.println("thread-name:" + threadName + "  phasee:" + ph.getPhase());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        ph.arriveAndDeregister();
    }
}